package com.yanq.liancar.activity;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;
import com.yanq.liancar.R;
import com.yanq.liancar.activity.base.BaseToolbarActivity;
import com.yanq.liancar.adapter.AgencyServiceAdapter;
import com.yanq.liancar.adapter.SmallBPayAdapter;
import com.yanq.liancar.bean.AgencyServiceBean;
import com.yanq.liancar.bean.PayNowBean;
import com.yanq.liancar.bean.PayResult;
import com.yanq.liancar.bean.ServiceAliPayBean;
import com.yanq.liancar.bean.ShopListBean;
import com.yanq.liancar.bean.UserBean;
import com.yanq.liancar.bean.WeChatPayBean;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.LogUtils;
import com.yanq.liancar.util.Utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class AgencyServiceActivity extends BaseToolbarActivity {
    @BindView(R.id.et_Contacts)
    EditText etContacts;
    @BindView(R.id.et_phone_num)
    EditText etPhoneNum;
    @BindView(R.id.et_serviceblurb)
    EditText etServiceblurb;
    @BindView(R.id.pay_recycleview)
    RecyclerView payRecycleview;
    @BindView(R.id.tv_recharge)
    TextView tvRecharge;
    @BindView(R.id.service_recuclerview)
    RecyclerView service_recuclerview;
    private List<PayNowBean> payNowBeanList = new ArrayList<>();
    private List<AgencyServiceBean.DataBean> mServiceBeanList = new ArrayList<>();
    private static final int SDK_PAY_FLAG = 1;
    private SmallBPayAdapter adapter;
    private AgencyServiceAdapter mAgencyServiceAdapter;
    private int type=2;    //type:支付方式
    private String dbType,dbName,dbPrice;
    private IWXAPI api;
    private static final String APP_ID="wxd2e19fc6b6f17ec0";
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**

                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。

                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    LogUtils.e("resultInfo====", resultInfo);
                    LogUtils.e("resultStatus====", resultStatus);
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        RxToast.success("下单成功");
                        finish();
                        //                        Bundle bundle=new Bundle();
                        //                        bundle.putString("orderID",orderID);
                        //                        RxActivityTool.skipActivityAndFinish(SmallCFuelFillingActivity.this, PurchaseSuccessActivity.class,bundle);
                    } else {

                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(AgencyServiceActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

            }

        }

    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Utils.setStatusBar(this, true, false);
        setContentView(R.layout.agencyservice);
        api = WXAPIFactory.createWXAPI(this,APP_ID);
        api.registerApp(APP_ID);
        ButterKnife.bind(this);
        mTvTitle.setText("代办服务");
        initData();
        initRecyclerView();
        getServicetype();
    }

    private void initData() {
        PayNowBean bean = new PayNowBean();
        bean.setNum(2);
        bean.setName("微信支付");
        bean.setChecked(true);
        payNowBeanList.add(bean);
        PayNowBean bean2 = new PayNowBean();
        bean2.setNum(1);
        bean2.setName("支付宝支付");
        bean2.setChecked(false);
        payNowBeanList.add(bean2);
    }

    private void initRecyclerView() {
        service_recuclerview.setNestedScrollingEnabled(false);
        service_recuclerview.setLayoutManager(new GridLayoutManager(this, 2));
        mAgencyServiceAdapter = new AgencyServiceAdapter(R.layout.item_agencyservice, mServiceBeanList);
        service_recuclerview.setAdapter(mAgencyServiceAdapter);
        mAgencyServiceAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                for (int i = 0; i < mServiceBeanList.size(); i++) {
                    if (position==i){
                        mServiceBeanList.get(i).setChecked(true);
                        dbType=mServiceBeanList.get(position).getDbType()+"";
                        dbName=mServiceBeanList.get(position).getDbName();
                        dbPrice=mServiceBeanList.get(position).getDbPrice()+"";
                    }else {
                        mServiceBeanList.get(i).setChecked(false);
                    }
                    mAgencyServiceAdapter.setNewData(mServiceBeanList);
                }
            }
        });


        payRecycleview.setNestedScrollingEnabled(false);
        payRecycleview.setLayoutManager(new LinearLayoutManager(this));
        adapter = new SmallBPayAdapter(R.layout.item_small_b_pay, payNowBeanList);
        payRecycleview.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                for (int i = 0; i < payNowBeanList.size(); i++) {
                    if (position == i) {
                        payNowBeanList.get(i).setChecked(true);
                        payNowBeanList.get(i).getName();
                        type = payNowBeanList.get(position).getNum();
                    } else {
                        payNowBeanList.get(i).setChecked(false);
                    }
                }
                adapter.setNewData(payNowBeanList);
            }
        });
    }

    private boolean isNull() {
        if (TextUtils.isEmpty(etContacts.getText().toString().trim())) {
            RxToast.error("请填写联系人");
            return false;
        }
        if (TextUtils.isEmpty(etPhoneNum.getText().toString().trim())) {
            RxToast.error("请填写手机号码");
            return false;
        }
        if (TextUtils.isEmpty(etServiceblurb.getText().toString().trim())) {
            RxToast.error("请填写地址");
            return false;
        }
        return true;
    }

    private void addStores() {
        if (isNull()) {
            OkGo.<String>post(Config.s + "llc//carServiceOrderController/insertAgentServiceOrder")
                    .tag(this)
                    .params("token", UserBean.getcToken(mContext))
                    .params("phone", etPhoneNum.getText().toString().trim())
                    .params("name", etContacts.getText().toString().trim())
                    .params("license_number", etServiceblurb.getText().toString().trim())
                    .params("payType", type)
                    .params("serviceType", dbType)
                    .params("serviceName", dbName)
                    .params("allPrice", dbPrice)
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                            Gson gson = new Gson();
                            if (type==1){
                                final ServiceAliPayBean baseBean = gson.fromJson(response.body(), ServiceAliPayBean.class);
                                if (baseBean.isIsSuccess()) {
                                    final String info = baseBean.getData().getSigned_content();
                                    LogUtils.e("加签info===", info);
                                    if ("".equals(info) || !TextUtils.isEmpty(info)) {
                                        Runnable payRunnable = new Runnable() {
                                            @Override
                                            public void run() {
                                                PayTask alipay = new PayTask(AgencyServiceActivity.this);
                                                Map<String, String> result = alipay.payV2(info, true);

                                                Message msg = new Message();
                                                msg.what = SDK_PAY_FLAG;
                                                msg.obj = result;
                                                mHandler.sendMessage(msg);

                                            }
                                        };
                                        // 必须异步调用
                                        Thread payThread = new Thread(payRunnable);
                                        payThread.start();
                                    }
                                } else {
                                    RxToast.error(baseBean.getOutputMessage());
                                }
                            }else if (type==2){
                                WeChatPayBean baseBean=gson.fromJson(response.body(),WeChatPayBean.class);
                                if (baseBean.isIsSuccess()){
                                    if (baseBean.getData()!=null){
                                        PayReq request = new PayReq();
                                        request.appId = baseBean.getData().getAppid();
                                        request.partnerId =baseBean.getData().getPartnerId();
                                        request.prepayId= baseBean.getData().getPrepayId();
                                        request.packageValue = baseBean.getData().getPackageValue();
                                        request.nonceStr= baseBean.getData().getNonceStr();
                                        request.timeStamp= baseBean.getData().getTimeStamp();
                                        request.sign= baseBean.getData().getSign();
                                        api.sendReq(request);
                                        finish();
                                        LogUtils.e(" api.sendReq=====",api.sendReq(request)+"");
                                    }
                                }else {
                                    RxToast.error("支付失败，请联系客服");

                                }
                            }
                        }
                    });
        }

    }

    @OnClick({R.id.tv_recharge,R.id.tv_message})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_recharge:
                LogUtils.e("asdasdad", UserBean.getcToken(this) + "");
                if (!"".equals(UserBean.getcToken(this)) && !TextUtils.isEmpty(UserBean.getcToken(this))) {
                    addStores();
                } else {
                    bottomDialog();
                }
                break;
            case R.id.tv_message:
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "4008055011"));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                break;
        }
    }

    //登陆验证
    private void bottomDialog() {
        final Dialog bottomDialog = new Dialog(this, R.style.BottomDialog);
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_landing_verification, null);
        bottomDialog.setContentView(contentView);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels;
        //        params.bottomMargin = MyUtils.dp2px(this, 8f);
        contentView.setLayoutParams(params);
        bottomDialog.getWindow().setGravity(Gravity.CENTER);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation2);
        bottomDialog.show();
        TextView tvTitle = bottomDialog.findViewById(R.id.title);
        tvTitle.setText("请先登录再购买服务");
        //确定
        TextView tv_confirm = bottomDialog.findViewById(R.id.submit);
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RxActivityTool.skipActivity(AgencyServiceActivity.this, LoginActivity.class);
                bottomDialog.dismiss();
            }
        });
        //取消
        TextView tv_cancle = bottomDialog.findViewById(R.id.cancel);
        tv_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bottomDialog.dismiss();
            }
        });
    }

    //查询代办服务类别
    private void getServicetype() {
        OkGo.<String>post(Config.s + "llc/platDbServerController/queryDbServerList")
                .tag(this)
                .params("serviceType", type)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        AgencyServiceBean baseBean = gson.fromJson(response.body(), AgencyServiceBean.class);
                        if (baseBean.isIsSuccess()) {
                            mServiceBeanList.clear();
                            mServiceBeanList.addAll(baseBean.getData());
                            mAgencyServiceAdapter.setNewData(mServiceBeanList);
                            LogUtils.e("mServiceBeanList",mServiceBeanList.size()+"");
                        } else {
                            RxToast.error(baseBean.getOutputMessage());
                        }
                    }
                });
    }
}
